<template>
  <el-row :gutter="6">
    <myAnnounceDlg @operationSucc="operationState($event)" :configs="myAnnounceDlgConfig"></myAnnounceDlg>
    <el-col :span="24" class="col-flex">
      <el-col class="breadcrumb-container">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/safety'}">安全控制</el-breadcrumb-item>
          <el-breadcrumb-item>安全检查</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
      <!-- 主要操作区域 -->
      <el-col v-loading="config.loading" class="maincont-container">
        <div class="tab-container" v-if="config.tabShow">
          <el-tabs v-model="tabConfig.activeName">
            <el-tab-pane name="todo">
              <span slot="label">
                我的待办
                <el-badge
                  v-if="config.todoCount>0"
                  :value="config.todoCount"
                  style="margin-left:2px"
                ></el-badge>
              </span>
              <my-tableX
                v-if="tabConfig.activeName==='todo'"
                :configs="todoConfig.configs"
                :tableData="todoConfig.data"
                @dataEdit="handleTodo"
              ></my-tableX>
            </el-tab-pane>
            <el-tab-pane :label="runningtablable" name="run">
              <my-tableX
                v-if="tabConfig.activeName==='run'"
                :configs="runingTaskConfig.configs"
                :tableData="runingTaskConfig.data"
                @dataAdd="addNewApply"
                @dataView="viewDetail"
              ></my-tableX>
            </el-tab-pane>
            <el-tab-pane label="历史记录" name="finish">
              <my-tableX
                v-if="tabConfig.activeName==='finish'"
                :configs="completedTaskConfig.configs"
                :tableData="completedTaskConfig.data"
                @dataView="viewDetail"
              ></my-tableX>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="flow-container" v-if="!config.tabShow">
          <div class="flow-step fix">
            <my-stepX :configs="flowConfig.stepConfig"></my-stepX>
          </div>
          <div class="flow-form scrollable">
            <el-form
              ref="flowFormData"
              :validate-on-rule-change="false"
              :model="flowFormData"
              label-width="0px"
              size="small"
              :rules="flowConfig.currentRule"
            >
              <h4 class="form-title">{{flowConfig.formTitle}}</h4>
              <table border="1px" cellpadding="0" cellspacing="0" class="form-data">
                <tr align="center">
                  <td class="form-label" colspan="1" width="10%">编号</td>
                  <td colspan="2" width="20%">
                    <el-input
                      placeholder="自动生成"
                      readonly
                      v-model="flowFormData.checkId"
                      size="small"
                    ></el-input>
                  </td>
                  <td class="form-label" colspan="2" width="20%">标段/勘察单位</td>
                  <td colspan="5" width="50%">
                    <el-input readonly type="text" size="small" v-model="flowFormData.tenders"></el-input>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="1" width="10%">选择检查标段</td>
                  <td colspan="9" width="90%">
                    <el-form-item label-width="0" :show-message="true" prop="checktender">
                      <el-select
                        v-model="checktender"
                        @change="changechecktender"
                        placeholder="选择检查标段"
                        :disabled="flowConfig.currentRule!=flowConfig.rules.node_1||flowConfig.formState.readonly"
                      >
                        <el-option
                          v-for="item in dictData.checktenderlist"
                          :key="item.tenders"
                          :label="item.tenders"
                          :value="item.tenders"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="1" width="10%">工程编号</td>
                  <td colspan="2" width="20%">
                    <el-form-item :show-message="false" prop="projectId">
                      <el-select
                        v-model="projectIdlable"
                        @change="changeProjectId"
                        placeholder="请选择工程编号"
                        :disabled="flowConfig.currentRule!=flowConfig.rules.node_1||flowConfig.formState.readonly"
                      >
                        <el-option
                          v-for="item in dictData.prolist"
                          :key="item.projectId"
                          :label="item.projectId"
                          :value="item.projectId"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="2" width="20%">工程名称</td>
                  <td colspan="5" width="50%">
                    <el-input
                      placeholder="自动填写"
                      v-model="flowFormData.projectName"
                      size="small"
                      readonly
                    ></el-input>
                  </td>
                </tr>
                <tr align="center">
                  <td class="form-label" colspan="1" width="10%">检查人</td>
                  <td colspan="1" width="10%">
                    <el-form-item label-width="0" :show-message="true" prop="inspectPerson">
                      <el-input
                        v-model="flowFormData.inspectPerson"
                        size="small"
                        :readonly="flowConfig.currentRule!=flowConfig.rules.node_1||flowConfig.formState.readonly"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="1" width="10%">检查时间</td>
                  <td colspan="2" width="20%">
                    <el-input readonly type="text" size="small" v-model="flowFormData.inspectTime"></el-input>
                  </td>
                  <td class="form-label" colspan="1" width="10%">回复人</td>
                  <td colspan="1" width="10%">
                    <el-form-item label-width="0" :show-message="true" prop="replier">
                      <el-input
                        size="small"
                        v-model="flowFormData.replier"
                        :readonly="flowConfig.currentRule!=flowConfig.rules.node_2||flowConfig.formState.readonly"
                      ></el-input>
                    </el-form-item>
                  </td>
                  <td class="form-label" colspan="1" width="10%">回复时间</td>
                  <td colspan="2" width="20%">
                    <el-input readonly type="text" size="small" v-model="flowFormData.replyTime"></el-input>
                  </td>
                </tr>
                <tr align="center" style="height:33px">
                  <td class="form-label" colspan="4" width="40%">检查内容</td>
                  <td class="form-label" colspan="2" width="20%">检查情况</td>
                  <td class="form-label" colspan="2" width="20%">整改回复</td>
                  <td class="form-label" colspan="2" width="20%">上传</td>
                </tr>
                <tr align="center" v-for="(item, index) in formDataDetail" :key="item.id">
                  <td class="form-label" colspan="1" width="10%">{{item.checkType}}</td>
                  <td align="left" class="form-label" colspan="3" width="30%">{{item.checkItem}}</td>
                  <td class="form-label" colspan="2" width="20%">
                    <el-input
                      type="textarea"
                      rows="3"
                      v-model="item.inspectProblem"
                      size="small"
                      :readonly="flowConfig.currentRule!=flowConfig.rules.node_1||flowConfig.formState.readonly"
                    ></el-input>
                  </td>
                  <td class="form-label" colspan="2" width="20%">
                    <el-input
                      type="textarea"
                      rows="3"
                      v-model="item.inspectReply"
                      size="small"
                      :readonly="flowConfig.currentRule!=flowConfig.rules.node_2||flowConfig.formState.readonly"
                    ></el-input>
                  </td>
                  <td class="form-label" colspan="2" width="20%">
                    <el-upload
                      :http-request="((item)=>{uploadSectionFile(item, index)})"
                      list-type="picture-card"
                      :limit="3"
                      :accept="filetype"
                      :before-upload="beforeUpload"
                      :before-remove="beforeRemove"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="((item)=>{handleRemove(item, fileList, index)})"
                      :on-exceed="handleExceed"
                      :file-list="fileList[index]"
                      v-if="showaddfile"
                      action="#"
                      multiple
                      :class="{hide:hideUpload[index]}"
                      :disabled="flowConfig.currentRule!=flowConfig.rules.node_1||flowConfig.formState.readonly"
                    >
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img v-if="ispic" width="100%" :src="dialogImageUrl" alt />
                      <video
                        v-if="!ispic"
                        width="100%"
                        :src="dialogImageUrl"
                        class="avatar"
                        controls="controls"
                      >您的浏览器不支持视频播放</video>
                    </el-dialog>
                  </td>
                </tr>
              </table>
              <el-form-item class="btns">
                <el-button
                  v-if="!flowConfig.formState.readonly"
                  @click="resolveflow"
                  type="primary"
                >{{flowConfig.currentBtn.resolveText}}</el-button>
                <!-- <el-button
                  v-if="!flowConfig.formState.readonly"
                  @click="rejectflow"
                  type="info"
                >{{flowConfig.currentBtn.rejectText}}</el-button>-->
                <el-button @click="cancelflow">{{flowConfig.currentBtn.cancelText}}</el-button>
              </el-form-item>
            </el-form>
          </div>
          <myExportTableBtn :configs="exportTableConfig"></myExportTableBtn>
          <!-- <div title="导出制式表格" class="addbutton-con">
            <el-button
              v-if="flowConfig.formState.readonly && flowState.step==3"
              @click="exportTable"
              type="primary"
              icon="el-icon-edit-outline"
              circle
            ></el-button>
          </div>-->
        </div>
      </el-col>
    </el-col>
  </el-row>
</template>


<script>
import myTableX from "@/components/base/tableX";
import myStepX from "@/components/base/stepX";
import { formatDate } from "@/utils/date";
import myAnnounceDlg from "@/components/base/announceDlg";
import httpfile from "@/api/file/index";
import fileType from "@/config/file.type.config";
import myExportTableBtn from "@/components/base/exportTableBtn";
// 全局变量
var glbVar = {};
var taskListParam = {};

var refRoles = []; //流程涉及到的角色列表

export default {
  inject: ["reload"],
  components: {
    myTableX,
    myStepX,
    myAnnounceDlg,
    myExportTableBtn,
  },

  // 初始化
  created() {
    this.$store.state.m_user.roles.forEach((item) => {
      if (item.id < 4 || item.id > 7) {
        this.myAnnounceDlgConfig.announceInfo.role.push(item.id);
      }
    });

    glbVar.subjectId = this.$store.state.projectInfo.projectName;
    glbVar.user = this.$store.state.m_user.userInfo;
    this.flowFormData.subjectId = glbVar.subjectId;
    this.flowTaskData.userid = glbVar.user.id;
    this.flowTaskData.path = this.$route.path;

    let query = this.$route.query;
    if (Object.keys(query).length != 0) {
      if (query.todo) {
        this.$api.securitycheck
          .getonly({ id: query.id })
          .then((res) => {
            if (res.code === 200) {
              this.handleTodo(res.data);
            } else {
              console.log("get todo business detail:" + res.msg);
            }
          })
          .catch((err) => {
            console.log("get todo business detail:" + err);
            this.$message.info("get todo business detail:" + err);
          });
      } else {
        this.$api.securitycheck
          .getonly({ id: query.remark })
          .then((res) => {
            if (res.code === 200) {
              this.viewDetail(res.data);
            } else {
              console.log("get todo business detail:" + res.msg);
            }
          })
          .catch((err) => {
            console.log("get todo business detail:" + err);
            this.$message.info("get todo business detail:" + err);
          });
      }
      this.config.tabShow = false;
    }
  },

  mounted() {
    console.log();

    taskListParam = {
      projectId: glbVar.subjectId,
      businessType: "8",
      userId: glbVar.user.id,
    };

    this.initList(taskListParam);

    //文件导出 是否可见
    this.exportTableConfig.isshown =
      this.flowConfig.formState.readonly && this.flowState.step == 3;
    this.exportTableConfig.subjectId = glbVar.subjectId;
  },

  watch: {
    $route(to, from) {
      if (to.path === from.path && to.query !== from.query) {
        this.initList(taskListParam);
      }
    },
    //文件导出 是否可见 监听变化
    "flowConfig.formState.readonly"(newstate, old) {
      this.exportTableConfig.isshown =
        this.flowConfig.formState.readonly && this.flowState.step == 3;
    },
    "flowState.step"(newstate, old) {
      if (newstate == 3) {
        this.exportTableConfig.isshown =
          this.flowConfig.formState.readonly && this.flowState.step == 3;
      }
    },
    flowFormData(newstate, old) {
      this.exportTableConfig.flowFormData = newstate;
    },
  },

  data() {
    let glbcolumns = [
      { field: "checkId", name: "文件编号" },
      { field: "tenders", name: "标段" },
      { field: "projectId", name: "工程编号" },
      { field: "projectName", name: "工程名称" },
      { field: "inspectPerson", name: "检查人" },
      { field: "inspectTime", name: "检查时间" },
      { field: "replier", name: "回复人" },
      { field: "replyTime", name: "回复时间" },
    ];
    return {
      //上传完成限制
      isUploadFinished: false,
      isSingleUploadFinished: true,
      fileListLength: [],

      filetype: fileType.fwQuality,
      //文件上传
      ispic: true, //是图片还是视频
      dialogImageUrl: "",
      dialogVisible: false,
      fileList: [],
      hideUpload: [],

      //标段信息
      kcdwnameData: "",
      //tab标签的lable
      runningtablable: "发起检查",
      //检查的标段对象
      checktender: "",

      //导出按钮Config
      exportTableConfig: {
        isshown: false,
        subjectId: glbVar.subjectId,
        model: 8,
        flowFormData: this.flowFormData,
      },

      config: {
        tabShow: true,
        todoCount: 0,
        loading: false,
      },
      tabConfig: {
        activeName: "todo",
      },
      todoConfig: {
        configs: {
          nodata: "暂无待办事项",
          columns: glbcolumns,
          showFilterRow: {
            show: true,
          },
          operationBtn: {
            show: true,
            // add: true,
            // addtext: "发起检查"
          },
          operationCol: {
            show: true,
            edit: true,
            options: {
              edit: {
                text: "处理",
              },
            },
          },
        },
        data: [],
      },
      runingTaskConfig: {
        configs: {
          nodata: "暂无运行记录",
          columns: glbcolumns,
          showFilterRow: {
            show: true,
          },
          operationBtn: {
            show: true,
            add: true,
            addtext: "发起检查",
          },
          operationCol: {
            show: true,
            view: true,
            options: {
              view: {
                text: "详情",
              },
            },
          },
        },
        data: [],
      },

      completedTaskConfig: {
        configs: {
          nodata: "暂无历史记录",
          columns: glbcolumns,
          showFilterRow: {
            show: true,
          },
          operationBtn: {
            show: false,
          },
          operationCol: {
            show: true,
            view: true,
            options: {
              view: {
                text: "详情",
              },
            },
          },
        },
        data: [],
      },

      //公告
      myAnnounceDlgConfig: {
        dialogFormVisible: false,
        isupdate: false,
        announceInfo: {
          remark: "",
          subject_id: "",
          url: "",
          notice_type: "安全检查",
          role: [],
          create_by: "",
          create_time: "",
          notice_content: "",
          notice_title: "安全检查完成",
          path: "",
          remark: "",
        },
      },
      flowState: {
        step: 0,
        executionId: null,
        flowNodeId: null,
        message: "",
        parent: 0,
        procInstId: null,
        userid: null,
      },

      flowConfig: {
        stepConfig: {
          active: 0,
          processstatus: "process",
          sequence: [],
          data: [
            { flow_node_name: "勘察总体发起安全检查", description: "" },
            { flow_node_name: "勘察单位回复安全检查", description: "" },
            { flow_node_name: "勘察总体确认回复", description: "" },
          ],
        },
        formTitle: "北京城市副中心站工程勘察外业安全检查表",
        currentRule: {},
        currentBtn: {
          resolveText: "发起",
          rejectText: "重置",
          cancelText: "返回",
        },
        rules: {
          node_1: {
            projectName: [{ required: true, trigger: "change" }],
            inspectPerson: [{ required: true, trigger: "blur" }],
          },
          node_2: {
            replier: [{ required: true, trigger: "blur" }],
          },
        },
        formState: {
          readonly: false,
        },
      },

      // 数据字典数据
      dictData: {
        //工程列表
        prolistOrg: [], //初始列表
        prolist: [], //运行列表
        checktenderlist: [],
      },

      currRecordTime: "",

      flowFormData: {},
      formDataDetail: [],
      projectIdlable: "",
      //flowComments: [],

      flowTaskData: {
        businessid: null,
        businesstype: 8,
        major: "",
        userid: null,
      },
    };
  },

  methods: {
    exportTable() {
      //数据准备
      // this.formDataDetail.forEach((item, index) => {
      //   if (this.fileList[index]) {
      //     item.url = this.fileList[index].join(";");
      //   }
      // });

      //this.flowFormData.giCheckSafeContentList = this.formDataDetail;
      console.log("look at me");
      console.log(this.flowFormData);

      this.$confirm("是否导出制式表格?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$api.exportTable
            .getUrl(
              {
                subjectId: glbVar.subjectId,
                model: 8,
              },
              this.flowFormData
            )
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("导出成功!");
                window.open(res.data.url);
                // this.listShow = !this.listShow;
                // this.initList();
              }
            })
            .catch((err) => {
              this.$message.error("导出失败!!" + err);
            });
        })
        .catch(() => {
          return;
        });
    },

    initList(taskListParam) {
      // 初始化工程数据列表
      // if (glbVar.user.roleId === 3) {
      this.$api.project
        .listBySubject(glbVar.subjectId)
        .then((res) => {
          console.log(res);
          if (res.code === 200) {
            this.dictData.prolistOrg = res.data;
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
      // }
      //初始化标段列表
      this.$api.project
        .queryTenders({ subjectId: glbVar.subjectId })
        .then((res) => {
          if (res.code === 200) {
            this.dictData.checktenderlist = res.data;
            this.kcdwnameData = res.data;
          }
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
      // //初始化检查项
      // this.$api.securitycheck
      //   .getcheckitems()
      //   .then(res => {
      //     if (res.code === 200) {
      //       this.formDataDetail = res.data;
      //     } else {
      //       console.log("get todo ids res:" + res.msg);
      //     }
      //   })
      //   .catch(err => {
      //     console.log("get todo ids res:" + err);
      //   });

      if (glbVar.user.roleId != 3) {
        this.runingTaskConfig.configs.operationBtn.add = false;
        this.runningtablable = "我已处理";
      }

      // 初始化列表
      this.$api.startitem
        .getmytasklist(taskListParam)
        .then((res) => {
          if (res.code === 200) {
            if (!res.data || res.data.length === 0) {
              this.todoConfig.data = [];
              // this.$message.info("暂无待办事项");
              return;
            }
            console.log(res);

            this.$api.securitycheck
              .getlist({ ids: res.data })
              .then((res) => {
                if (res.code === 200) {
                  this.todoConfig.data = res.data;
                } else {
                  console.log("get todo business detail:" + res.msg);
                }
              })
              .catch((err) => {
                console.log("get todo business detail:" + err);
                this.$message.info("get todo business detail:" + err);
              });
          } else {
            console.log("get todo ids res:" + res.msg);
          }
        })
        .catch((err) => {
          console.log("get todo ids res:" + err);
        });

      this.$api.startitem
        .getprocessinglist(taskListParam)
        .then((res) => {
          if (res.code === 200) {
            console.log("lenght:" + res.data.length);

            if (!res.data || res.data.length === 0) {
              this.runingTaskConfig.data = [];
              // this.$message.info("暂无运行流程");
              return;
            }
            this.$api.securitycheck
              .getlist({ ids: res.data })
              .then((res) => {
                if (res.code === 200) {
                  this.runingTaskConfig.data = res.data;
                } else {
                  console.log("get runing business detail:" + res.msg);
                }
              })
              .catch((err) => {
                console.log("get runing business detail:" + err);
                this.$message.info("get runing business detail:" + err);
              });
          }
        })
        .catch((err) => {
          console.log("get runing ids res:" + err);
        });
      this.$api.startitem
        .getfinishedlist(taskListParam)
        .then((res) => {
          console.log(res);

          if (res.code === 200) {
            if (!res.data || res.data.length === 0) {
              this.completedTaskConfig.data = [];
              // this.$message.info("暂无历史流程");
              return;
            }
            this.$api.securitycheck
              .getlist({ ids: res.data })
              .then((res) => {
                if (res.code === 200) {
                  console.log("his");
                  console.log(res.data);

                  this.completedTaskConfig.data = res.data;
                } else {
                  console.log("get finished business detail:" + res.msg);
                }
              })
              .catch((err) => {
                console.log("get finished business detail:" + err);
                this.$message.info("get finished business detail:" + err);
              });
          }
        })
        .catch((err) => {
          console.log("get finished business detail:" + err);
        });
    },

    //监听上传公告结果
    operationState(msg) {
      console.log(msg);
      if (msg) {
        this.$message.success("发布成功");
        this.config.tabShow = true;
      } else {
        this.$message.error("发布失败");
      }
      this.initList(taskListParam);
      this.config.loading = false;
    },

    /**
     * @description: 发起一个变更申请,预操作
     */
    addNewApply() {
      this.flowFormData = {};
      this.formDataDetail = {};
      this.projectIdlable = "";
      this.checktender = "";
      // this.formDataDetail.forEach(item => {
      //   item.inspectProblem = "";
      //   item.inspectReply = "";
      // })
      //初始化检查项
      // this.$api.securitycheck
      //   .getcheckitems()
      //   .then(res => {
      //     if (res.code === 200) {
      //       this.formDataDetail = res.data;
      //     } else {
      //       console.log("get todo ids res:" + res.msg);
      //     }
      //   })
      //   .catch(err => {
      //     console.log("get todo ids res:" + err);
      //   });

      this.flowConfig.formState.readonly = false;
      this.flowConfig.stepConfig.active = 0;
      this.config.tabShow = false;
      this.flowConfig.currentRule = this.flowConfig.rules.node_1;
      this.flowFormData.inspectTime = formatDate(
        new Date(),
        "yyyy-MM-dd hh:mm:ss"
      );
      this.flowFormData.tenders =
        glbVar.user.nick_name + "/" + glbVar.user.company;
      this.flowFormData.subjectId = glbVar.subjectId;
      this.flowFormData.subjectName = glbVar.subjectId;
    },

    /**
     * @description: 处理待办任务
     */
    handleTodo(row) {
      // this.currRecordTime = row.recordingDate;
      this.fileList = [];
      let id = row.id;
      this.flowFormData = row;
      this.projectIdlable = row.projectId;
      this.formDataDetail = row.giCheckSafeContentList;
      // this.initComments(id);
      console.log(this.formDataDetail);

      //读取文件url
      this.formDataDetail.forEach((item, index) => {
        if (item.url != "") {
          item.url.split(";").forEach((it) => {
            if (it != "") {
              if (!this.fileList[index]) {
                this.fileList[index] = [];
              }
              let b = it.split("/");
              this.fileList[index].push({
                name: b.slice(b.length - 1, b.length).toString(String),
                url: it,
              });
            }
          });
        }
      });

      // 初始化公告默认角色列表
      this.$api.startitem.getRoleByRuningInfo(8, id).then((res) => {
        if (res.code === 200) {
          refRoles = res.data;
        }
      });

      this.$api.startitem
        .getworkflow({
          businessType: 8,
          businessId: id,
        })
        .then((res) => {
          if (res.code === 200) {
            let { id, proc_inst_id } = res.data;
            this.$api.startitem
              .getcurrentstage({
                executionId: id,
                procInstId: proc_inst_id,
              })
              .then((res) => {
                if (res.code === 200) {
                  this.flowConfig.formState.readonly = false;
                  this.flowConfig.stepConfig.active = res.data[0];
                  this.changeStep(res.data[0]);

                  this.flowState.executionId = id;
                  this.flowState.flowNodeId = res.data[1];
                  this.flowState.message = "";
                  this.flowState.procInstId = proc_inst_id;
                  this.flowState.time = formatDate(
                    new Date(),
                    "yyyy-MM-dd hh:mm:ss"
                  );
                  this.flowState.userid = glbVar.user.id;

                  this.flowFormData.replyTime = formatDate(
                    new Date(),
                    "yyyy-MM-dd hh:mm:ss"
                  );

                  this.config.tabShow = false;
                }
              });
          }
        });
    },

    // 查看流程运行详情,运行时
    viewDetail(row) {
      console.log(row);
      this.fileList = [];

      let id = row.id;
      this.flowFormData = row;
      this.projectIdlable = row.projectId;
      this.formDataDetail = row.giCheckSafeContentList;

      //读取文件url
      this.formDataDetail.forEach((item, index) => {
        if (item.url != "") {
          item.url.split(";").forEach((it) => {
            if (it != "") {
              if (!this.fileList[index]) {
                this.fileList[index] = [];
              }
              let b = it.split("/");
              this.fileList[index].push({
                name: b.slice(b.length - 1, b.length).toString(String),
                url: it,
              });
            }
          });
        }
      });
      // this.initComments(id);
      this.$api.startitem
        .getworkflow({
          businessType: 8,
          businessId: id,
        })
        .then((res) => {
          if (res.code === 200) {
            let { id, proc_inst_id } = res.data;
            this.$api.startitem
              .getcurrentstage({
                executionId: id,
                procInstId: proc_inst_id,
              })
              .then((res) => {
                if (res.code === 200) {
                  this.flowConfig.formState.readonly = true;
                  this.flowConfig.stepConfig.active = res.data[0];
                  this.changeStep(res.data[0]);
                  this.config.tabShow = false;
                }
              });
          }
        });

      //确定模板
      if (this.flowFormData.major === "勘察") {
        this.exportTableConfig.model = 801;
      } else if (this.flowFormData.major === "水文") {
        this.exportTableConfig.model = 802;
      }
      console.log(this.exportTableConfig);
    },

    changeStep(step) {
      console.log("step:" + step);
      this.flowState.step = step;
      this.flowConfig.currentRule = this.flowConfig.rules["node_" + (step + 1)];

      if (step === 0) {
        this.flowConfig.currentBtn = {
          resolveText: "发送",
          cancelText: "返回",
        };
      } else if (step === 1) {
        // this.flowFormData.recordingDate = this.currRecordTime;
        this.flowConfig.currentBtn = {
          resolveText: "回复",
          cancelText: "取消",
        };
      } else {
        this.flowConfig.currentBtn = {
          resolveText: "确认",
          cancelText: "取消",
        };
      }

      if (step === 1 && !this.flowConfig.formState.readonly) {
        this.flowFormData.overallConfirmingDate = formatDate(
          new Date(),
          "yyyy-MM-dd hh:mm:ss"
        );
      } else {
        if (step === 2 && !this.flowConfig.formState.readonly) {
          this.flowFormData.ownerConfirmingDate = formatDate(
            new Date(),
            "yyyy-MM-dd hh:mm:ss"
          );
        }
      }
    },
    changeProjectId(value) {
      this.dictData.prolist.forEach((item) => {
        if (item.projectId === value) {
          this.flowFormData.projectId = item.projectId;
          this.projectIdlable = item.projectId;

          this.flowFormData.projectName = item.projectName;
          this.flowTaskData.major = item.major;

          this.flowFormData.major = item.major;
          this.kcdwnameData.forEach((it, index) => {
            if (it.tenders === item.tenders) {
              this.flowTaskData.userid = it.userId;
            }
          });

          //初始化检查项
          this.$api.securitycheck
            .getcheckitems({ major: this.flowFormData.major })
            .then((res) => {
              if (res.code === 200) {
                this.formDataDetail = res.data;
              } else {
                console.log("get todo ids res:" + res.msg);
              }
            })
            .catch((err) => {
              console.log("get todo ids res:" + err);
            });

          return;
        }
      });
    },
    changechecktender(value) {
      console.log(this.checktender);
      this.flowFormData.projectId = "";
      this.flowFormData.projectName = "";
      this.projectIdlable = "";
      this.dictData.prolist = this.dictData.prolistOrg[this.checktender];

      console.log("我是change checktender");
      console.log(this.flowFormData);
    },
    // changeProjectName(value) {
    //   this.dictData.prolist.forEach(item => {
    //     if (item.projectName === value) {
    //       console.log(item);
    //       this.flowFormData.projectId = item.projectId;
    //       this.flowFormData.major = item.major;

    //       this.flowTaskData.major = item.major;

    //       this.kcdwnameData.forEach((it, index) => {
    //         if (it.tenders === item.tenders) {
    //           this.flowTaskData.userid = it.userId;
    //         }
    //       });

    //       return;
    //     }
    //   });
    // },

    // 执行流程
    resolveflow() {
      //查看每一列有没有没传完的文件
      this.isSingleUploadFinished = true;
      for (var i = 0; i < this.fileList.length; i++) {
        if (!this.fileList[i]) {
          this.fileList[i] = [];
        }

        if (!this.fileListLength[i]) {
          this.fileListLength[i] = 0;
        }

        if (this.fileListLength[i] != this.fileList[i].length) {
          console.log("有不对的");

          console.log(i);
          console.log(this.fileListLength);
          console.log(this.fileList);

          this.isSingleUploadFinished = false;
        }
        if (this.isSingleUploadFinished) {
          console.log("炒鸡");
          this.isUploadFinished = true;
        }
      }

      if (!this.isUploadFinished) {
        console.log("return UploadFinished");
        this.$message.warning("文件未上传完毕，请稍后重试！");
        return;
      }

      // 预验证
      this.$refs.flowFormData.validate((res) => {
        if (res) {
          this.$confirm("提交操作后不可更改，是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.handleResolve();
            })
            .catch(() => {
              return;
            });
        } else {
          this.$message.warning("请检查必填项");
        }
      });
    },

    handleResolve() {
      if (this.flowState.step === 0) {
        this.config.loading = true;
        console.log("新增");

        //写url先
        this.formDataDetail.forEach((item, index) => {
          if (this.fileList[index]) {
            item.url = this.fileList[index].join(";");
            console.log(this.fileList[index]);
          }
        });

        console.log(this.formDataDetail);

        // this.formDataDetail.url = this.fileList
        //     .map(item => {
        //       return (
        //         "/" +
        //         this.$store.state.projectInfo.projectName +
        //         "/安全检查/" +
        //         item.name
        //       );
        //     })
        //     .join(";");
        this.flowFormData.giCheckSafeContentList = this.formDataDetail;
        console.log("我是具体工作量");

        console.log(this.flowFormData);

        this.$api.securitycheck
          .add(this.flowFormData)
          .then((res) => {
            console.log("add seurity res");
            console.log(res);
            if (res.code === 200) {
              this.flowTaskData.businessid = res.data;
              this.$api.startitem
                .starttask(this.flowTaskData)
                .then((res) => {
                  this.config.loading = false;
                  console.log(res);

                  if (res.code === 200) {
                    this.$message.success("发送成功：已发送至标段");
                    this.config.tabShow = true;
                    this.initList(taskListParam);
                  } else {
                    this.$message.error("发送失败：" + res.msg);
                  }
                })
                .catch((err) => {
                  this.$message.error("发送失败：" + err);
                });
            } else {
              this.config.loading = false;
              this.$message.error("提交表单失败:" + res.msg);
            }
          })
          .catch((err) => {
            this.config.loading = false;
            this.$message.error("提交表单失败:" + err);
          });
      } else {
        // 走审批接口
        console.log("我是更新");

        this.flowFormData.giCheckSafeContentList.forEach((item, index) => {
          if (this.fileList[index]) {
            item.url = this.fileList[index]
              .map((item) => {
                return (
                  "/" +
                  this.$store.state.projectInfo.projectName +
                  "/安全检查/" +
                  item.name
                );
              })
              .join(";");
          }
        });

        this.$api.securitycheck.modify(this.flowFormData).then((res) => {
          if (res.code === 200) {
            this.flowState.approver = this.currApproveInfo.approver;
            this.$api.startitem.approve([this.flowState]).then((res) => {
              console.log("approve param");
              console.log(this.flowState);
              if (res.code === 200) {
                this.$message.success("操作成功");
                if (this.flowState.step === 2) {
                  // //添加公告
                  // this.myAnnounceDlgConfig.isupdate = false;
                  // this.myAnnounceDlgConfig.announceInfo.create_by = this.flowFormData.inspectPerson;
                  // this.myAnnounceDlgConfig.announceInfo.remark = this.flowFormData.id;
                  // this.myAnnounceDlgConfig.announceInfo.subject_id =
                  //   glbVar.subjectId;
                  // this.myAnnounceDlgConfig.announceInfo.notice_content =
                  //   "安全检查内容";
                  // this.myAnnounceDlgConfig.dialogFormVisible = true;
                  let announce = {
                    subject_id: this.flowFormData.subjectId,
                    url: "",
                    remark: this.flowFormData.id,
                    notice_type: "安全检查",
                    role: refRoles,
                    create_by: this.flowFormData.inspectPerson,
                    create_time: this.flowFormData.inspectTime,
                    notice_content:
                      "【" +
                      this.flowFormData.tenders.split("/")[0] +
                      "】安全检查审核完成",
                    notice_title:
                      "【" +
                      this.flowFormData.tenders.split("/")[0] +
                      "】安全检查审核完成",
                    path: this.$route.path,
                  };

                  this.$api.announce
                    .add(announce)
                    .then((res) => {
                      this.config.loading = false;
                      if (res.code == 200) {
                        this.$message.success("操作成功!");
                        this.config.tabShow = true;
                        this.initList(taskListParam);
                      } else {
                        this.$message.error("操作失败!" + res.msg);
                      }
                    })
                    .catch((err) => {
                      this.config.loading = false;
                      this.$message.error("操作失败!" + err);
                    });
                } else {
                  this.config.tabShow = true;
                  this.initList(taskListParam);
                  if (this.$route.query === {}) {
                    this.initList(taskListParam);
                  } else {
                    this.$router.replace({
                      path: this.$route.path,
                      query: {},
                    });
                  }
                }
                // this.config.tabShow = true;
                // if (this.$route.query === {}) {
                //   this.initList(taskListParam);
                // } else {
                //   this.$router.replace({
                //     path: this.$route.path,
                //     query: {}
                //   });
                //   this.initList(taskListParam);
                // }
              }
            });
          }
        });
      }
    },

    // initComments(id) {
    //   this.$api.startitem
    //     .getcomment({ businessType: 3, businessId: id })
    //     .then(res => {
    //       if (res.code === 200) {
    //         console.log("get comment data res.data:" + res.data);
    //         this.flowComments = res.data;
    //       } else {
    //         console.log("get comment data err res.msg:" + res.msg);
    //       }
    //     })
    //     .catch(err => {
    //       console.log("get comment data err:" + err);
    //     });
    // },

    // 取消流程
    cancelflow() {
      this.config.tabShow = true;
      this.flowFormData = {};
    },

    //文件上传
    handleRemove(file, fileList, index) {
      let num = this.fileList[index].indexOf(file.response.config.params.path);
      this.fileList[index].splice(num, 1);
      console.log("我是长度：" + this.fileList[index].length);
      if (this.fileList[index].length < 4) {
        this.hideUpload[index] = false;
      } else {
        this.hideUpload[index] = true;
      }
      console.log(this.hideUpload[index]);
      this.fileListLength[index] -= 1;
    },
    handlePictureCardPreview(file) {
      console.log(file);
      let filetag = "";

      this.dialogImageUrl = file.url;
      if (this.flowState.step === 0) {
        filetag = file.raw.name.substring(file.raw.name.lastIndexOf(".") + 1);
      } else {
        filetag = file.url.substring(file.url.lastIndexOf(".") + 1);
      }

      //判断是图片还是视频
      if (
        ["png", "jpg", "pdf", "jpeg", "PNG", "JPG", "PDF", "JPEG"].indexOf(
          filetag
        ) > -1
      ) {
        this.ispic = true;
      } else {
        this.ispic = false;
      }

      //this.dialogImageUrl = "http://39.106.121.254:5031" + file.response.config.params.path;
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      if (this.filetype.indexOf("." + testmsg.toLowerCase()) < 0) {
        this.$message({
          message: "上传文件格式不符合要求：" + testmsg,
          type: "warning",
        });
        return false;
      }
      return true;
    },
    uploadSectionFile(params, index) {
      this.isUploadFinished = false;

      if (!this.fileListLength[index]) {
        this.fileListLength[index] = 1;
      } else {
        this.fileListLength[index] += 1;
      }
      console.log(this.fileListLength[index]);

      // const uid = params.file.uid;
      let keyname =
        formatDate(new Date(), "yyyyMMddhhmmss") +
        Math.floor(Math.random() * 1000);
      const fileData = new FormData();
      fileData.append("file", params.file);
      const query = {
        path:
          "/" +
          this.$store.state.projectInfo.projectName +
          "/安全检查/" +
          keyname +
          params.file.name,
      };

      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          token: window.sessionStorage.getItem("token"),
        },
        // 这一段代码解决进度条不显示的问题，属于 axios 的使用知识。具体可以看文末的参考链接。
        // onUploadProgress: progressEvent => {
        //   const percentCompleted = Math.floor(
        //     (progressEvent.loaded * 100) / progressEvent.total
        //   );
        //   params.onProgress({ percent: percentCompleted });
        // }
      };

      httpfile.upload(query, config, fileData).then((res) => {
        // console.log(res);
        // console.log("[index]:" + this.fileList[index]);
        if (res.status == 200) {
          if (!this.fileList[index]) {
            this.fileList[index] = [];
          }

          this.fileList[index].push(query.path);
          params.onSuccess(res);

          console.log("我是长度：" + this.fileList[index].length);
          if (this.fileList[index].length > 3) {
            this.hideUpload[index] = true;
            console.log(this.hideUpload[index]);
          }
          console.log(this.fileList);
        }
      });
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多选择 4 个文件");
    },
  },

  computed: {
    currApproveInfo() {
      let index = this.flowState.step;
      if (index === 1) {
        return {
          approver: this.flowFormData.replier,
        };
      } else {
        return {
          approver: this.flowFormData.inspectPerson,
        };
      }
    },
    showaddfile() {
      // console.log(this.fileList);

      // if (this.fileList.length > 2) {
      //   return false;
      // } else {
      //   return true;
      // }
      return true;
    },
  },
};
</script>



<style lang='less' scoped>
.col-flex {
  box-sizing: border-box;
  padding-top: 30px;
  height: 100%;

  .breadcrumb-container {
    height: 30px;
    margin-top: -20px;
  }

  .maincont-container {
    height: 100%;
    margin-top: 3px;
    .tab-container {
      height: 100%;
      /deep/.el-tabs {
        height: 100%;

        .el-tabs__header {
          margin: 0;
        }
        .el-tabs__content {
          height: calc(~"100% - 40px");
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
    .flow-container {
      height: 100%;
      width: 100%;
      box-sizing: border-box;
      padding-top: 60px;

      .flow-step {
        width: 100%;
        height: 60px;
        margin-top: -60px;
      }

      .flow-form {
        text-align: center;
        height: calc(~"100% - 10px");
        // height: 100%;

        table .form-label {
          background-color: #efefef;
        }

        .form-title {
          margin: 10px !important;
        }

        .form-data {
          border-collapse: collapse;
          margin: auto;
          width: 70%;
          font-size: 13px;
        }
        .btns {
          width: 70%;
          margin: 20px auto;
          display: flex;
          justify-content: flex-end;
        }
      }
    }
  }

  .scrollable {
    overflow: auto;
  }

  /deep/.el-form-item {
    padding: 0px;
    margin: 0px;
    .el-form-item__content {
      line-height: normal;
    }
    .el-select {
      display: block;
    }
  }

  //调整上传的样式
  /deep/.el-upload {
    width: 50px;
    height: 50px;
  }
  /deep/.el-upload--picture-card i {
    margin-top: 10px;
  }
  /deep/.el-upload--picture-card {
    line-height: 0%;
  }
  /deep/.el-upload-list--picture-card .el-upload-list__item {
    width: 50px;
    height: 50px;
    margin: 0;
  }
  /deep/.el-upload-list--picture-card
    .el-upload-list__item-actions
    span
    + span {
    margin: 0%;
  }
  /deep/.addbutton-con {
    button {
      box-shadow: 0px 0px 0px 3px #66b1ff55;
    }
    i {
      font-size: 20px;
    }
    z-index: 100;
    position: absolute;
    top: 10px;
    right: 10px;
    margin: 5px;
    height: 40px;
    border-radius: 50%;
    // box-shadow: 0px 0px 0px 2px gray;
  }
}
</style>